import React, {FC, useEffect, useMemo, useRef, useState} from "react";
import QuestionCard from "../../../components/QuestionCard";
import styles from '../index.module.scss'
import { useTitle, useThrottleFn, useRequest } from 'ahooks'
import { Empty, Spin, Typography } from "antd";
import ListSearch from "../../../components/ListSearch";
import useLoadQuestionListData from "../../../hooks/useLoadQuestionListData";
import { useSearchParams } from "react-router-dom";
import { getQuestionListService } from "../../../service/questions";
import { LIST_PAGE_SIZE, LIST_SEARCH_PARAM_KEY } from "../../../constant";

const { Title } = Typography

const List:FC = () => {
  useTitle('LUABU问卷 — 我的问卷')
  
  const [started, setStarted] = useState(false) //标记是否开始已经加载
  const [list, setList] = useState([])
  const [page, setPage] = useState(1) //全部的列表数据，上划加载更多
  const [total, setTotal] = useState(0)
  const [searchParams] = useSearchParams()
  const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''
  const haveMoreData = total > list.length
  
  //keyword变化的时候重置信息
  useEffect(() => {
    setStarted(false)
    setPage(1)
    setList([])
    setTotal(0)
  }, [keyword])
  //加载
  const { run: load, loading} = useRequest(async () => {
    const data = await getQuestionListService({
      page,
      pageSize: LIST_PAGE_SIZE,
      keyword: keyword
    })
    return data
  },
  {
    manual: true,
    onSuccess(result) {
      const {list: l = [] , total = 0} = result
      setList(list.concat(l))
      setTotal(total)
      setPage(page+1)
    }
  })

  //触发加载 节流
  const containerRef = useRef<HTMLDivElement>(null)
  const { run: tryLoadMore} = useThrottleFn(() => {
    const elem = containerRef.current
    if(elem == null) return
    const domRect = elem.getBoundingClientRect()
    if (domRect == null) return
    const { bottom } = domRect
    if (bottom <= document.body.clientHeight){
      load()
      setStarted(true)
    }
  },{
    wait:1000
  })
  //页面加载，或url变化，触发加载
  useEffect(() => {
    tryLoadMore() //加载第一页
  },[searchParams])

  //页面滚动时触发加载
  useEffect(() => {
    if (haveMoreData){
      window.addEventListener('scroll',tryLoadMore)
    }
    return () => {
      window.removeEventListener('scroll',tryLoadMore)
    }
  },[searchParams, haveMoreData])

  const loadMoreContentElem = useMemo(() => {
    if (!started || loading) return <Spin/>
    if (total === 0) return <Empty description="暂无数据"/>
    if (!haveMoreData) return <Empty description="没有更多了"/>
    return <span>加载下一页</span>
  },[started, loading, haveMoreData])
  return <>
    <div className={styles.header}>
      <div className={styles.left}>
        <Title level={3}>我的问卷</Title>
      </div>
      <div className={ styles.right }>
        <ListSearch />
      </div>
    </div>
    <div className={styles.content}>
      
      {
         list.length > 0 && list.map((question: any) => {
          const {_id} = question 
          return <QuestionCard key={_id} {...question}/>
        })
      }
    </div>
    <div className={styles.footer}>
      <div ref={containerRef} >
        { loadMoreContentElem}
      </div>
    </div>
  </>
}

export default List;